﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Drivers;

namespace WevPanel
{
    public partial class FormMain : Form
    {
        public static SerialDriver SerialDriver_ { get; set; } = new SerialDriver();
        public FormOllioscope Ollioscope;
        public FormUserCurves CurveEditor;
        public FormAntiCog AntiCog;
        public FormConsole WevConsole;
        public TreeNode SlaveTree = new TreeNode(nameof(SerialDriver_.Slave.WevDriver));
        public Queue<float> VelList = new Queue<float>();
        public FormMain()
        {
            InitializeComponent();
        }

        private void RefreshPorts()
        {
            comboSerials.Items.Clear();
            foreach (var item in Transport.ListPorts())
            {
                comboSerials.Items.Add(item);
            }
            if(comboSerials.Items.Count > 0)
            {
                comboSerials.SelectedIndex = 0;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Ollioscope = new FormOllioscope();
            CurveEditor = new FormUserCurves();
            AntiCog = new FormAntiCog();
            WevConsole = new FormConsole();
            WevConsole.OnSendCommand += (cmd) => {
                SerialDriver_.SendMsg(cmd);
            };
            WevConsole.FormClosing += (sen, ev) =>
            {
                WevConsole.Hide();
                timerBk.Start();
                ev.Cancel = true;
            };
            RefreshPorts();
            timerBk.Start();
            propertyMaster.SelectedObject = SerialDriver_.Master;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshPorts();
            AntiCog.RefreshPorts();
            propertyMaster.SelectedObject = SerialDriver_.Master;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            SerialDriver_.Begin(comboSerials.Text, 9600);
            SerialDriver_.StartRead();
            checkSET.Checked = false;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            SerialDriver_.Close();
        }

        private void timerBk_Tick(object sender, EventArgs e)
        {
            btnClose.Enabled = SerialDriver_.Ready;
            btnOpen.Enabled = !SerialDriver_.Ready;
            propertySlave.SelectedObject = SerialDriver_.Slave;
            if (SerialDriver_.Ready)
            {
                if(SerialDriver_.DownloadingPidCurve)
                {
                    SerialDriver_.DownloadPidCurve();
                }
                else
                    SerialDriver_.HeartBeat();
            }

            propertyMaster.Enabled = checkSET.Checked;
            SerialDriver_.Master.WevHeartBeatMaster.EnableSetting = checkSET.Checked?(byte)1:(byte)0;
            if(!checkSET.Checked)
            {
                /* 仅在使能修改的时候可以修改参数，否则读取驱动器参数 */
                SerialDriver_.Master.WevHeartBeatMaster.FeedForwardRatio = SerialDriver_.Slave.WevDriver.FeedForwardRatio;
            }

            if (SerialDriver_.Master.WevHeartBeatMaster.SetPids == 0)
            {
                SerialDriver_.Master.WevHeartBeatMaster.Pids = SerialDriver_.Slave.WevDriver.Pids;
            }
            if (SerialDriver_.Master.WevHeartBeatMaster.Enable == 0)
            {
                SerialDriver_.Master.WevHeartBeatMaster.PosSetpoint = SerialDriver_.Slave.WevDriver.Encoder.ActualPos;
            }

            VelList.Enqueue(SerialDriver_.Slave.WevDriver.Encoder.RpmFiltered);
            if (VelList.Count > 50) VelList.Dequeue();
            SerialDriver_.Slave._FilteredVel = VelList.Average();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SerialDriver_.Dispose();
        }

        private void btnEnable_Click(object sender, EventArgs e)
        {
            ButtonOnOff(btnEnable,
                () => {
                    SerialDriver_.Master.WevHeartBeatMaster.VelSetpoint = 0;
                    SerialDriver_.Master.WevHeartBeatMaster.SetPids = 0;
                    SerialDriver_.Master.WevHeartBeatMaster.Enable = 1; 
                },
                () => { SerialDriver_.Master.WevHeartBeatMaster.Enable = 0; }
                );
        }

        /// <summary>
        /// C#反射遍历对象属性
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="model">对象</param>
        public void ForeachClassProperties<T>(T model, TreeNode node)
        {
            Type t = model.GetType();
            PropertyInfo[] PropertyList = t.GetProperties();
            node.Nodes.Clear();
            foreach (PropertyInfo item in PropertyList)
            {
                string name = item.Name;
                //object value = item.GetValue(model, null);
                Console.WriteLine(name);
                node.Nodes.Add(name, name);
                if (item.PropertyType.IsPrimitive)
                {
                    Console.WriteLine(item.PropertyType.Name);
                }
                else
                {
                    object value = item.GetValue(model, null);
                    ForeachClassProperties(value, node.Nodes[name]);
                }
            }
        }

        private void btnScope_Click(object sender, EventArgs e)
        {
            ForeachClassProperties(SerialDriver_.Slave.WevDriver, SlaveTree);
            Ollioscope.Show();
            Ollioscope.UpdateTree(SlaveTree);
        }

        private void propertyMaster_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            propertyMaster.SelectedObject = SerialDriver_.Master;
        }

        private void btnSetPids_Click(object sender, EventArgs e)
        {
            ButtonOnOff(btnSetPids, 
                () => { 
                    SerialDriver_.Master.WevHeartBeatMaster.SetPids = 1;
                    SerialDriver_.Master.WevHeartBeatMaster.AutoPid = 0;
                }, 
                () => {
                    SerialDriver_.Master.WevHeartBeatMaster.SetPids = 0; }
                );
        }

        private void ButtonOnOff(Button btn, Action on, Action off)
        {
            if (btn.BackColor != Color.LightGreen)
            {
                btn.BackColor = Color.LightGreen;
                on();
            }
            else
            {
                btn.BackColor = Control.DefaultBackColor;
                off();
            }
            propertyMaster.SelectedObject = SerialDriver_.Master;
        }

        private void btnEditCurve_Click(object sender, EventArgs e)
        {
            CurveEditor.Show();
        }

        private void btnMore_Click(object sender, EventArgs e)
        {
            MoreButtons.Show(MousePosition);
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            SerialDriver_.Master.WevHeartBeatMaster.Reset = 1;
            Task.Run(() =>
            {
                Thread.Sleep(500);
                SerialDriver_.Master.WevHeartBeatMaster.Reset = 0;
            });
        }

        private void antiCogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AntiCog.Show();
        }

        private void consoleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            timerBk.Stop();
            WevConsole.Show();
        }
    }

}
